import { apiProxy } from "@/util/request";

export default {
    state: {
        cartGoods: []
    },
    getters: {
        getCartGoods(state) {
            return state.cartGoods
        }
    },
    mutations: {
        getCart(state, goods) {
            state.cartGoods = goods
        }
    },
    actions: {
        updateCartAsync({commit},data){
            console.log(commit);
            return new Promise((resolve) => {
                apiProxy({
                    url: `/api/cart/`,
                    method: "put",
                    data
                }).then(res => {
                    console.log(res);
                    if(res.code==0){
                        this.dispatch("getCartAsync").then(res => {
                            console.log('购物车更新数据完毕', res);
                        })
                    }
                    resolve("更新成功")
                })
            })
        },
        addCartAsync({ commit }, data) {
            console.log(commit);
            return new Promise((resolve) => {
                // console.log(data);
                apiProxy({
                    url: "/api/cart/",
                    method: "post",
                    data
                }).then(res => {
                    console.log(res);
                    if (res.code == 0) {
                        // data有数据企鹅必须没有达到最大数量
                        // insertId 为0 代表更新
                        // insertId 为1 代表插入
                        this.dispatch("getCartAsync").then(res => {
                            console.log('购物车更新数据完毕', res);
                        })
                        resolve(res)
                    }
                })

            })
        },
        getCartAsync({ commit }) {
            return new Promise((resolve) => {
                apiProxy({
                    url: "/api/cart",
                    method: "get"
                }).then(res => {
                    if (res.code == 0) {
                        commit("getCart", res.data)
                    }
                    resolve(res)
                })
            })
        },
        deletCartAsync({ commit }, id) {
            console.log(commit);
            return new Promise((resolve) => {
                apiProxy({
                    url: `/api/cart/${id}`,
                    method: "delete"
                }).then(res => {
                    if (res.code == 0) {
                        this.dispatch("getCartAsync").then(res => {
                            console.log('购物车更新数据完毕', res);
                        })
                    }
                    resolve("删除成功")
                })
            })
        }
    },
    modules: {
    }
}
